<template>
  <view class="address-list-page">
    <!-- 新增地址按钮 -->
    <view class="add-address-header">
      <view class="add-btn" :style="{background: themeColorStyles.primaryColor, boxShadow: themeColorStyles.addBtnShadow}" @click="addAddress">
        <text class="add-icon">+</text>
        <text class="add-text">新增收货地址</text>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="content-container">
      <!-- 加载状态 -->
      <view v-if="loading" class="loading-container">
        <view class="loading-item" v-for="n in 3" :key="n">
          <view class="loading-header">
            <view class="loading-text name"></view>
            <view class="loading-text phone"></view>
          </view>
          <view class="loading-text address"></view>
        </view>
      </view>
      
      <!-- 地址列表 -->
      <view class="address-list" v-else-if="addressList.length > 0">
        <view 
          class="address-card" 
          v-for="address in addressList" 
          :key="address.id"
          :class="{ 'default': address.isDefault }"
          :style="address.isDefault ? {border: themeColorStyles.defaultCardBorder, boxShadow: themeColorStyles.defaultCardShadow} : {boxShadow: themeColorStyles.cardShadow, border: themeColorStyles.cardBorder}"
        >
          <!-- 默认标签 -->
          <view class="default-badge" :style="{background: themeColorStyles.primaryColor, boxShadow: themeColorStyles.defaultBadgeShadow}" v-if="address.isDefault">
            <text class="badge-text">默认</text>
          </view>
          
          <!-- 地址信息 -->
          <view class="address-info">
            <view class="address-header">
              <text class="recipient-name">{{ address.name }}</text>
              <text class="recipient-phone">{{ address.phone }}</text>
            </view>
            <text class="address-detail">
              {{ address.provinceName }}{{ address.cityName }}{{ address.areaName }}{{ address.detail }}
            </text>
          </view>
          
          <!-- 操作按钮 -->
          <view class="address-actions">
            <view class="action-btn edit-btn" :style="{background: themeColorStyles.editBtnBg, border: themeColorStyles.editBtnBorder}" @click="editAddress(address)">
              <text class="btn-text" :style="{color: themeColorStyles.primaryColor}">编辑</text>
            </view>
            <view class="action-btn delete-btn" @click="deleteAddress(address.id)">
              <text class="btn-text">删除</text>
            </view>
            <view 
              class="action-btn default-btn" 
              v-if="!address.isDefault"
              @click="setDefault(address.id)"
            >
              <text class="btn-text">设为默认</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-container" v-else-if="!loading && !error && addressList.length === 0">
        <view class="empty-content">
          <text class="empty-icon">📍</text>
          <text class="empty-text">暂无收货地址</text>
          <text class="empty-desc">添加收货地址，享受便捷购物体验</text>
          <view class="empty-action" :style="{background: themeColorStyles.primaryColor, boxShadow: themeColorStyles.emptyActionShadow}" @click="addAddress">
            <text class="action-text">添加地址</text>
          </view>
        </view>
      </view>
      
      <!-- 错误状态 -->
      <view class="error-container" v-else-if="error && !loading">
        <view class="error-content">
          <text class="error-icon">⚠️</text>
          <text class="error-text">加载失败</text>
          <text class="error-desc">{{ errorMessage }}</text>
          <view class="error-action" @click="retryLoad">
            <text class="action-text">重试</text>
          </view>
        </view>
      </view>
      
      <!-- 兜底显示内容，防止白屏 -->
      <view class="fallback-container" v-else>
        <view class="fallback-content">
          <text class="fallback-text">正在加载收货地址...</text>
        </view>
      </view>
      

      
      <!-- 底部间距 -->
      <view class="bottom-space"></view>
    </view>
  </view>
</template>

<script>
import { listUserAddress, delUserAddress, setDefaultAddress } from '@/api/address'
import { getUserInfo } from '@/utils/auth'
import { handleApiError } from '@/utils/loginCheck'
import { getThemePrimaryColor, getThemeColorFromGlobal } from '@/utils/theme'

export default {
  data() {
    return {
      // 地址列表数据
      addressList: [],
      // 加载状态
      loading: false,
      // 错误状态
      error: false,
      errorMessage: '',
      // 用户ID（从登录信息获取）
      userId: null,
      // 页面是否已初始化
      isPageInitialized: false,
      // 防止重复加载的标志
      isLoading: false,
      primaryColor: '#4A90E2'
    };
  },
  
  async onLoad() {
    // 异步执行，避免阻塞页面渲染
    this.$nextTick(async () => {
      await this.initThemeColor();
      this.initPage();
    });
    
    // 监听地址变更事件
    uni.$on('addressChanged', this.handleAddressChanged);
  },
  
  onUnload() {
    // 移除事件监听
    uni.$off('addressChanged', this.handleAddressChanged);
  },
  
  computed: {
    themeColorStyles() {
      return this.setThemeColorVariables(this.primaryColor)
    }
  },
  
  onShow() {
    // 只有在页面已经初始化过且不在加载中的情况下才重新加载
    if (this.isPageInitialized && !this.isLoading && this.userId) {
      this.loadAddressList(false); // 不显示loading
    }
  },
  
  methods: {
    // 初始化主题色
    async initThemeColor() {
      const themeColor = await getThemeColorFromGlobal()
      this.primaryColor = getThemePrimaryColor(themeColor)
      console.log('收货地址页面主题色:', themeColor, this.primaryColor)
    },
    
    // 设置主题色变量
    setThemeColorVariables(color) {
      const rgb = this.hexToRgb(color)
      
      return {
        primaryColor: color,
        primaryColorLight: this.lightenColor(color, 20),
        primaryColorShadow: `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.3)`,
        primaryColorBorder: `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.1)`,
        primaryColorBgLight: `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.1)`,
        backgroundGradient: `linear-gradient(180deg, ${this.lightenColor(color, 0.95)} 0%, ${this.lightenColor(color, 0.92)} 100%)`,
        cardShadow: `0 8rpx 32rpx rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.08)`,
        cardBorder: `1rpx solid rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.1)`,
        defaultCardBorder: `2rpx solid ${color}`,
        defaultCardShadow: `0 8rpx 24rpx rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.15)`,
        defaultBadgeShadow: `0 4rpx 12rpx rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.3)`,
        addBtnShadow: `0 8rpx 24rpx rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.2)`,
        editBtnBg: `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.1)`,
        editBtnBorder: `1rpx solid rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.2)`,
        emptyActionShadow: `0 4rpx 16rpx rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.15)`,
        '--primary-color': color,
        '--card-bg-color': '#FFFFFF',
        '--card-border-color': `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.2)`,
        '--page-bg-color': '#F8FAFC',
        '--text-secondary-color': '#64748B'
      }
    },
    
    // 十六进制颜色转RGB
    hexToRgb(hex) {
      const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
      return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
      } : { r: 74, g: 144, b: 226 }
    },
    
    // 颜色变亮（支持百分比和小数）
    lightenColor(color, amount) {
      const rgb = this.hexToRgb(color)
      if (!rgb) return color
      
      // 如果amount大于1，认为是百分比，否则认为是小数
      const factor = amount > 1 ? amount / 100 : amount
      
      const r = Math.min(255, Math.floor(rgb.r + (255 - rgb.r) * factor))
      const g = Math.min(255, Math.floor(rgb.g + (255 - rgb.g) * factor))
      const b = Math.min(255, Math.floor(rgb.b + (255 - rgb.b) * factor))
      
      return `#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${b.toString(16).padStart(2, '0')}`
    },
    
    // 初始化页面
    async initPage() {
      // 获取用户ID
      await this.getUserId();
      if (!this.userId) {
        this.error = true;
        this.errorMessage = '用户未登录';
        return;
      }
      
      await this.loadAddressList();
    },
    
    // 处理地址变更事件
    handleAddressChanged(data) {
      console.log('收到地址变更事件:', data);
      // 刷新地址列表
      if (this.userId) {
        this.loadAddressList(false); // 不显示loading
      }
    },
    
    // 获取用户ID - 简化版本，参考购物车页面
    getUserId() {
      try {
        // 优先从store获取
        const storeUserId = this.$store && this.$store.state && this.$store.state.user && this.$store.state.user.id;
        
        if (storeUserId && storeUserId !== 'default' && storeUserId !== '') {
          this.userId = storeUserId;
          return storeUserId;
        }
        
        // 从storage_data获取
        const storageData = uni.getStorageSync('storage_data') || {};
        const userId = storageData['user_id'] || storageData['userId'];
        
        if (userId && userId !== 'default' && userId !== '') {
          this.userId = userId;
          return userId;
        }
        
        // 最后尝试从userId存储获取
        const fallbackUserId = uni.getStorageSync('userId');
        
        if (fallbackUserId && fallbackUserId !== 'default' && fallbackUserId !== '') {
          this.userId = fallbackUserId;
          return fallbackUserId;
        }
        
        return null;
      } catch (error) {
        return null;
      }
    },
    
    // 加载地址列表
    async loadAddressList(showLoading = true) {
      // 防止重复调用
      if (this.isLoading && showLoading) {
        return;
      }
      
      // 获取用户ID - 参考购物车页面的方式
      const userId = this.getUserId();
      
      if (!userId) {
        this.error = true;
        this.errorMessage = '请先登录';
        return;
      }
      
      if (showLoading) {
        this.loading = true;
        this.isLoading = true;
      }
      this.error = false;
      this.errorMessage = '';
      
      try {
        // 调用API获取用户地址列表
        const response = await listUserAddress({
          userId: this.userId
        });
        
        console.log('API响应:', response);
        
        // 统一错误处理
        if (response.code === 401) {
          this.error = true;
          this.errorMessage = '登录状态已过期，请重新登录';
          // 避免调用handleApiError，防止触发弹窗导致页面重新加载
          return;
        }
        
        if (response.code === 200) {
          const rawData = response.data || response.rows || [];
          console.log('API返回的原始数据:', rawData);
          
          // 将数据库字段转换为前端使用的驼峰命名
          this.addressList = rawData.map(item => {
            console.log('处理单个地址项:', item);
            const mappedItem = {
              id: item.id || item.addressId,
              name: item.consignee_name || item.receiverName || item.consignee || item.name,
              phone: item.consignee_phone || item.receiverPhone || item.mobile || item.phone,
              provinceCode: item.province,
              provinceName: item.province_name || item.provinceName || item.province,
              cityCode: item.city,
              cityName: item.city_name || item.cityName || item.city,
              areaCode: item.district,
              areaName: item.district_name || item.areaName || item.district,
              detail: item.detail_address || item.detailAddress || item.detail,
              isDefault: item.is_default === 1 || item.is_default === '1' || item.isDefault === '1' || item.isDefault === 1
            };
            console.log('映射后的地址项:', mappedItem);
            return mappedItem;
          });
          console.log('最终地址列表:', this.addressList);
        } else {
          this.error = true;
          this.errorMessage = response.msg || '获取地址列表失败';
          uni.showToast({
            title: this.errorMessage,
            icon: 'none'
          });
        }
      } catch (error) {
        this.error = true;
        
        // 根据错误类型设置不同的错误信息
        if (error.response && error.response.status === 401) {
          this.errorMessage = '登录状态已过期，请重新登录';
        } else if (error.response && error.response.status === 403) {
          this.errorMessage = '没有权限访问该功能';
        } else if (error.response && error.response.status >= 500) {
          this.errorMessage = '服务器错误，请稍后重试';
        } else {
          this.errorMessage = '网络错误，请检查网络连接';
        }
        
        // 只在showLoading为true时显示toast，避免重复提示
        if (showLoading) {
          uni.showToast({
            title: this.errorMessage,
            icon: 'none'
          });
        }
      } finally {
        this.loading = false;
        if (showLoading) {
          this.isLoading = false;
        }
      }
    },
    
    // 添加地址
    addAddress() {
      uni.navigateTo({
        url: '/pages/address/edit'
      });
    },
    
    // 编辑地址
    editAddress(address) {
      uni.navigateTo({
        url: `/pages/address/edit?id=${address.id}&data=${encodeURIComponent(JSON.stringify(address))}`
      });
    },
    
    // 删除地址
    async deleteAddress(id) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这个收货地址吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              const response = await delUserAddress(id);
              
              if (response.code === 200) {
                uni.showToast({
                  title: '删除成功',
                  icon: 'success'
                });
                // 重新加载地址列表
                this.loadAddressList();
              } else {
                uni.showToast({
                  title: response.msg || '删除失败',
                  icon: 'none'
                });
              }
            } catch (error) {
              console.error('删除地址异常:', error);
              uni.showToast({
                title: '网络错误，请重试',
                icon: 'none'
              });
            }
          }
        }
      });
    },
    
    // 设为默认地址
    async setDefault(id) {
      try {
        const response = await setDefaultAddress(id);
        
        if (response.code === 200) {
          uni.showToast({
            title: '设置成功',
            icon: 'success'
          });
          // 重新加载地址列表以更新默认状态
          this.loadAddressList();
        } else {
          uni.showToast({
            title: response.msg || '设置失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('设置默认地址异常:', error);
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      }
    },
    
    // 重试加载
    retryLoad() {
      // 重置错误状态和加载标志
      this.error = false;
      this.errorMessage = '';
      this.isLoading = false;
      this.loadAddressList();
    }
  }
};
</script>

<style scoped>
/* 页面整体样式 */
.address-list-page {
  min-height: 100vh;
  background: #F5F5F5;
  display: flex;
  flex-direction: column;
}

/* 移除动画以提高小程序兼容性 */
/* @keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
} */

/* 内容区域 */
.content-container {
  flex: 1;
  padding: 16rpx 32rpx 0;
  min-height: calc(100vh - 120rpx);
  box-sizing: border-box;
}

/* 地址列表样式 */
.address-list {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
  padding-bottom: 60rpx;
}

.address-card {
  background: #FFFFFF;
  border-radius: 24rpx;
  padding: 32rpx 24rpx;
  position: relative;
  transition: all 0.3s ease;
}

.address-card:active {
  transform: scale(0.98);
}

/* 默认标签 */
.default-badge {
  position: absolute;
  top: 0;
  right: 24rpx;
  /* 简化渐变为纯色以提高小程序兼容性 */
  padding: 8rpx 16rpx;
  border-radius: 0 0 12rpx 12rpx;
}

.badge-text {
  font-size: 20rpx;
  color: #FFFFFF;
  font-weight: 600;
}

/* 地址信息 */
.address-info {
  margin-bottom: 24rpx;
}

.address-header {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
  gap: 24rpx;
}

.recipient-name {
  font-size: 32rpx;
  font-weight: 600;
  color: #1A1A1A;
}

.recipient-phone {
  font-size: 28rpx;
  color: #666666;
}

.address-detail {
  font-size: 26rpx;
  color: #666666;
  line-height: 1.5;
}

/* 操作按钮 */
.address-actions {
  display: flex;
  gap: 16rpx;
  justify-content: flex-end;
}

.action-btn {
  padding: 12rpx 24rpx;
  border-radius: 20rpx;
  transition: all 0.3s ease;
}

.action-btn:active {
  transform: scale(0.95);
}

.edit-btn {
  /* styles moved to inline */
}

.delete-btn {
  background: rgba(255, 107, 107, 0.1);
  border: 1rpx solid #FF6B6B;
}

.default-btn {
  background: rgba(52, 199, 89, 0.1);
  border: 1rpx solid #34C759;
}

.btn-text {
  font-size: 24rpx;
  font-weight: 500;
}

.edit-btn .btn-text {
  color: #4A90E2;
}

.delete-btn .btn-text {
  color: #FF6B6B;
}

.default-btn .btn-text {
  color: #34C759;
}

/* 空状态样式 */
.empty-container {
  background: #FFFFFF;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.04);
  border: 1rpx solid rgba(74, 144, 226, 0.08);
}

.empty-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80rpx 40rpx;
}

.empty-icon {
  font-size: 80rpx;
  margin-bottom: 24rpx;
}

.empty-text {
  font-size: 32rpx;
  color: #1A1A1A;
  margin-bottom: 12rpx;
  font-weight: 600;
}

.empty-desc {
  font-size: 26rpx;
  color: #8A8A8A;
  margin-bottom: 32rpx;
  text-align: center;
  line-height: 1.5;
}

.empty-action {
  /* 简化渐变为纯色以提高小程序兼容性 */
  padding: 16rpx 32rpx;
  border-radius: 24rpx;
  /* 简化过渡效果 */
  transition: all 0.3s ease;
}

.empty-action:active {
  transform: scale(0.95);
}

.action-text {
  font-size: 28rpx;
  color: #FFFFFF;
  font-weight: 600;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
  padding-bottom: 60rpx;
}

.loading-item {
  background: #FFFFFF;
  border-radius: 24rpx;
  padding: 32rpx 24rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.04);
  border: 1rpx solid rgba(74, 144, 226, 0.08);
}

.loading-header {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
  gap: 24rpx;
}

.loading-text {
  /* 简化加载动画，使用纯色背景 */
  background: #f0f0f0;
  border-radius: 8rpx;
  /* 移除复杂动画以提高小程序兼容性 */
}

.loading-text.name {
  width: 120rpx;
  height: 32rpx;
}

.loading-text.phone {
  width: 200rpx;
  height: 28rpx;
}

.loading-text.address {
  width: 100%;
  height: 26rpx;
}

/* 移除复杂的loading动画 */
/* @keyframes loading {
  0% {
    background-position: 200% 0;
  }
  100% {
    background-position: -200% 0;
  }
} */

/* 错误状态样式 */
.error-container {
  background: #FFFFFF;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.04);
  border: 1rpx solid rgba(255, 107, 107, 0.08);
}

.error-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80rpx 40rpx;
}

.error-icon {
  font-size: 80rpx;
  margin-bottom: 24rpx;
}

.error-text {
  font-size: 32rpx;
  color: #FF6B6B;
  margin-bottom: 12rpx;
  font-weight: 600;
}

.error-desc {
  font-size: 26rpx;
  color: #8A8A8A;
  margin-bottom: 32rpx;
  text-align: center;
  line-height: 1.5;
}

.error-action {
  /* 简化渐变为纯色以提高小程序兼容性 */
  background: #FF6B6B;
  padding: 16rpx 32rpx;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(255, 107, 107, 0.3);
  /* 简化过渡效果 */
  transition: all 0.3s ease;
}

.error-action:active {
  transform: scale(0.95);
}

/* 兜底显示样式 */
.fallback-container {
  background: #FFFFFF;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.04);
  border: 1rpx solid rgba(74, 144, 226, 0.08);
}

.fallback-content {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 80rpx 40rpx;
}

.fallback-text {
  font-size: 28rpx;
  color: #666666;
}

/* 底部间距 */
.bottom-space {
  height: 60rpx;
}



/* 新增地址按钮样式 */
.add-address-header {
  padding: 20rpx 32rpx;
  background: #FFFFFF;
  border-bottom: 1rpx solid #F0F0F0;
}

.add-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 88rpx;
  border-radius: 12rpx;
  transition: all 0.3s ease;
}

.add-btn:active {
  transform: scale(0.98);
  box-shadow: 0 2rpx 8rpx rgba(74, 144, 226, 0.4);
}

.add-icon {
  font-size: 36rpx;
  color: #FFFFFF;
  font-weight: 300;
  margin-right: 12rpx;
}

.add-text {
  font-size: 32rpx;
  color: #FFFFFF;
  font-weight: 500;
}
</style>